package com.lekang.system.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lekang.common.annotation.Log;
import com.lekang.common.core.controller.BaseController;
import com.lekang.common.core.domain.AjaxResult;
import com.lekang.common.enums.BusinessType;
import com.lekang.common.utils.SecurityUtils;
import com.lekang.system.domain.AccraditationRecord;
import com.lekang.system.service.IAccraditationRecordService;
import com.lekang.common.utils.poi.ExcelUtil;
import com.lekang.common.core.page.TableDataInfo;
import java.util.Date;

/**
 * 审批记录Controller
 * 
 * @author zihao
 * @date 2025-10-18
 */
@RestController
@RequestMapping("/system/record")
public class AccraditationRecordController extends BaseController
{
    @Autowired
    private IAccraditationRecordService accraditationRecordService;

    /**
     * 查询审批记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:record:list')")
    @GetMapping("/list")
    public TableDataInfo list(AccraditationRecord accraditationRecord)
    {
        startPage();
        // 权限过滤：非管理员只能查看与自己相关的审批记录
        Long currentUserId = SecurityUtils.getUserId();
        System.out.println("=== 审批记录权限过滤 ===");
        System.out.println("当前用户ID: " + currentUserId);
        System.out.println("前端传入的approverId: " + accraditationRecord.getApproverId());
        
        // 只有超级管理员（ID=1）才能查看所有记录
        if (!currentUserId.equals(1L)) {
            // 其他用户（包括护理组组长ID=101）只能看到自己作为审批人的记录
            // 强制设置，忽略前端传入的任何approverId参数
            accraditationRecord.setApproverId(currentUserId);
            System.out.println("非管理员权限：强制设置approverId = " + currentUserId);
        } else {
            System.out.println("管理员权限：不限制查询");
        }
        
        List<AccraditationRecord> list = accraditationRecordService.selectAccraditationRecordList(accraditationRecord);
        System.out.println("查询结果数量: " + (list != null ? list.size() : 0));
        return getDataTable(list);
    }

    /**
     * 导出审批记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:record:export')")
    @Log(title = "审批记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AccraditationRecord accraditationRecord)
    {
        // 权限过滤：非管理员只能导出与自己相关的审批记录
        Long currentUserId = SecurityUtils.getUserId();
        // 只有超级管理员（ID=1）才能导出所有记录
        if (!currentUserId.equals(1L)) {
            // 其他用户（包括护理组组长ID=101）只能导出自己作为审批人的记录
            accraditationRecord.setApproverId(currentUserId);
        }
        
        List<AccraditationRecord> list = accraditationRecordService.selectAccraditationRecordList(accraditationRecord);
        ExcelUtil<AccraditationRecord> util = new ExcelUtil<AccraditationRecord>(AccraditationRecord.class);
        util.exportExcel(response, list, "审批记录数据");
    }

    /**
     * 获取审批记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:record:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(accraditationRecordService.selectAccraditationRecordById(id));
    }

    /**
     * 新增审批记录
     */
    // @PreAuthorize("@ss.hasPermi('system:record:add')")
    @Log(title = "审批记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AccraditationRecord accraditationRecord)
    {
        return toAjax(accraditationRecordService.insertAccraditationRecord(accraditationRecord));
    }

    /**
     * 修改审批记录
     */
    @PreAuthorize("@ss.hasPermi('system:record:edit')")
    @Log(title = "审批记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AccraditationRecord accraditationRecord)
    {
        return toAjax(accraditationRecordService.updateAccraditationRecord(accraditationRecord));
    }

    /**
     * 删除审批记录
     */
    @PreAuthorize("@ss.hasPermi('system:record:remove')")
    @Log(title = "审批记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(accraditationRecordService.deleteAccraditationRecordByIds(ids));
    }
    
    /**
     * 审批提交 - 新增审批记录（专用于审批页面提交）
     */
    // @PreAuthorize("@ss.hasPermi('system:record:add')")
    @Log(title = "审批提交", businessType = BusinessType.INSERT)
    @PostMapping("/submit")
    public AjaxResult submitApproval(@RequestBody AccraditationRecord accraditationRecord)
    {
        System.out.println("=== 审批提交开始 ===");
        System.out.println("接收到的审批数据: " + accraditationRecord);
        
        try {
            Long userId = SecurityUtils.getUserId();
            String currentUsername = SecurityUtils.getUsername();
            Long tuizhushenpiyuana = 100L; // 退住审批员用户ID
            
            // ✅ 权限控制：只有退住审批员a (tuizhushenpiyuana) 才能进行退住审批操作
            System.out.println("=== 审批权限检查 ===");
            System.out.println("当前用户: " + currentUsername);
            System.out.println("当前用户ID: " + userId);
            
            if (!"tuizhushenpiyuana".equals(currentUsername)) {
                System.out.println("❌ 非退住审批员a，禁止进行退住审批操作");
                return error("只有退住审批员a才能进行退住审批操作");
            }
            
            System.out.println("✅ 退住审批员a，允许进行退住审批操作");
            
            // 设置审批记录字段
            accraditationRecord.setFinishTime(new Date()); // 完成时间为当前时间
            accraditationRecord.setType(1L); // 审批类型：1（退住）
            accraditationRecord.setApproverId(userId); // 审批人ID：登录角色的ID
            accraditationRecord.setApproverName(SecurityUtils.getLoginUser().getUser().getUserName()); // 审批人：登录角色的账号
            accraditationRecord.setApproverNameRole(SecurityUtils.getLoginUser().getUser().getNickName()); // 审批人角色：登录角色的昵称
            accraditationRecord.setNextApproverId(tuizhushenpiyuana); // 下一个审核人ID固定为100
            accraditationRecord.setNextApprover("tuizhushenpiyuana"); // 下一个审核人固定为tuizhushenpiyuana
            accraditationRecord.setNextApproverRole("退住审批员"); // 下一个审核人角色固定为退住审批员
            accraditationRecord.setCurrentStep("审批申请"); // 当前操作步骤：审批申请
            accraditationRecord.setNextStep("解除合同"); // 下一步操作描述：解除合同
            accraditationRecord.setStepNo(2L); // ✅ 当前步骤是2，不是3
            // ✅ 不要覆盖前端传递的 handleType（即待办任务ID ptid）
            // accraditationRecord.setHandleType(1L); // ❌ 删除这行，保留前端传递的值
            
            System.out.println("审批人ID: " + accraditationRecord.getApproverId());
            System.out.println("待办任务ID (ptid): " + accraditationRecord.getHandleType());
            System.out.println("审批人账号: " + accraditationRecord.getApproverName());
            System.out.println("审批人昵称: " + accraditationRecord.getApproverNameRole());
            System.out.println("审批意见: " + accraditationRecord.getOpinion());
            System.out.println("审核状态: " + accraditationRecord.getAuditStatus());
            System.out.println("业务ID: " + accraditationRecord.getBussniessId());
            System.out.println("当前步骤: " + accraditationRecord.getStepNo());
            
            // ✅ 保存审批记录（Service层会处理所有工作流逻辑）
            int result = accraditationRecordService.insertAccraditationRecord(accraditationRecord);
            System.out.println("审批记录插入结果: " + result);
            
            System.out.println("=== 审批提交完成 ===");
            
            return toAjax(result);
        } catch (Exception e) {
            System.out.println("审批提交异常: " + e.getMessage());
            e.printStackTrace();
            return error("审批提交失败：" + e.getMessage());
        }
    }
}
